package com.link.base.base.message.push.service;

import com.alibaba.fastjson.JSONObject;
import com.link.base.base.message.push.dao.mybatis.mapper.PushMapper;
import com.link.base.base.message.push.model.PushInfo;
import com.link.core.cllog.LCLogger;
import com.link.core.kafka.KafkaTemplateFacotry;
import com.link.core.kafka.conf.KafkaEnv;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

/**
 * web端消息推送
 *
 * @author ouyangzhenqiang
 * @date 2019/07/25 17:24
 */
@Component
public class WebPushServiceImpl {
    @Resource
    private PushMapper pushMapper;

    /**
     * 用于定时工作流
     *
     * @author ouyangzhenqiang
     * @date 2018/10/26
     * @param list
     */
    public void webPushList(List<PushInfo> list) throws Exception {
        try {
            for (PushInfo item : list) {
                sendSocketMessage(item);
                pushMapper.updateWebPushResult(item);
            }
        } catch (Exception e) {
            LCLogger.withException(e);
            throw new Exception("服务器异常：" + e.toString());
        }
    }

    /**
     * 立即推送
     *
     * @author ouyangzhenqiang
     * @date 2019/07/25 17:43
     */
    public void webPushRightWay(PushInfo record) throws Exception {
        try {
            sendSocketMessage(record);
            pushMapper.updateWebPushResult(record);
        } catch (Exception e) {
            LCLogger.withException(e);
            throw new Exception("服务器异常：" + e.toString());
        }
    }

    /**
     * 发送消息到kafka，传递至websocket服务
     * 
     * @author 欧阳振强
     * @date 2020/01/14
     */
    private void sendSocketMessage(PushInfo record) throws Exception {
        if (KafkaEnv.isEnabled()) {
            try {
                JSONObject object = new JSONObject();
                object.put("action", "SendMessageAction");
                object.put("identifier", "web");
                object.put("interaction", record.getUserId());
                JSONObject message = new JSONObject();
                message.put("type", "text");
                message.put("title", record.getPushTitle());
                message.put("content", record.getPushNote());
                object.put("message", message);
                KafkaTemplateFacotry.send("websocket", object.toString());
            } catch (Exception e) {
                LCLogger.withException(e.getMessage());
            }
        } else {
            LCLogger.withException("kafka server is not available!");
        }
    }
}
